﻿using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Xml;

namespace Sarnata.Common.Providers.BaseCamp
{
    public class BaseCampConnection
    {
        public const string REQUESTMETHOD_GET = "get";
        public const string REQUESTMETHOD_POST = "post";
        public const string REQUESTMETHOD_PUT = "put";
        public const string REQUESTMETHOD_DELETE = "delete";
        public const string PREFIX_SECURE = "https://";
        public const string PREFIX_NOTSECURE = "http://";
        public const string MIMETYPE_APPLICATIONXML = "application/xml";

        public enum RequestMethod { Get, Post, Put, Delete }

        private string _username = String.Empty;
        private string _password = String.Empty;
        private string _clientURL = String.Empty;

        public string Username
        {
            get
            {
                return _username;
            }
            set
            {
                if (_username == value)
                    return;
                _username = value;
            }
        }
        public string Password
        {
            get
            {
                return _password;
            }
            set
            {
                if (_password == value)
                    return;
                _password = value;
            }
        }
        public string ClientURL
        {
            get
            {
                return _clientURL;
            }
            set
            {
                if (_clientURL == value)
                    return;
                _clientURL = value;
            }
        }
        
        public BaseCampConnection()
        {
        }
        
        public BaseCampConnection(string clientURL, string username, string password)
        {
            _clientURL = clientURL;    
            _username = username;
            _password = password;
        }

        public XmlDocument SendSecureGetRequest(string command, string request)
        {
            return SendRequest(command, request, true, RequestMethod.Get);
        }

        public XmlDocument SendSecurePostRequest(string command, string request)
        {
            return SendRequest(command, request, true, RequestMethod.Post);
        }

        public XmlDocument SendSecurePutRequest(string command, string request)
        {
            return SendRequest(command, request, true, RequestMethod.Put);
        }

        public XmlDocument SendSecureDeleteRequest(string command, string request)
        {
            return SendRequest(command, request, true, RequestMethod.Delete);
        }

        public XmlDocument SendGetRequest(string command, string request)
        {
            return SendRequest(command, request, false, RequestMethod.Get);
        }

        public XmlDocument SendPostRequest(string command, string request)
        {
            return SendRequest(command, request, false, RequestMethod.Post);
        }

        public XmlDocument SendPutRequest(string command, string request)
        {
            return SendRequest(command, request, false, RequestMethod.Put);
        }

        public XmlDocument SendDeleteRequest(string command, string request)
        {
            return SendRequest(command, request, false, RequestMethod.Delete);
        }

        private string getRequestMethodValue(RequestMethod requestMethod)
        {
            switch (requestMethod)
            {
            	case RequestMethod.Get:
            		return REQUESTMETHOD_GET;
            	case RequestMethod.Post:
            		return REQUESTMETHOD_POST;
            	case RequestMethod.Put:
            		return REQUESTMETHOD_PUT;
            	case RequestMethod.Delete:
            		return REQUESTMETHOD_DELETE;
            }
            return REQUESTMETHOD_GET;
        }

        public XmlDocument SendRequest(string command, string request, bool secureMode, RequestMethod method)
        {
            XmlDocument returnVal = new XmlDocument();
            try
            {
                string prefix = (secureMode) ? PREFIX_SECURE : PREFIX_NOTSECURE;
                string url = string.Concat(prefix, _clientURL, command);

                HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                webRequest.Method = getRequestMethodValue(method);
                webRequest.Accept = MIMETYPE_APPLICATIONXML;
                webRequest.ContentType = MIMETYPE_APPLICATIONXML;
                webRequest.Credentials = new NetworkCredential(_username, _password);
                webRequest.ServicePoint.Expect100Continue = false;

                if (method != RequestMethod.Get)
                    using (StreamWriter sw = new StreamWriter(webRequest.GetRequestStream()))
                        sw.WriteLine(request);

                WebResponse webResponse = webRequest.GetResponse();
                using (Stream responseStream = webResponse.GetResponseStream())
                    using (StreamReader sr = new StreamReader(responseStream))
                    {
                        returnVal.Load(sr.BaseStream);
                        sr.Close();
                    }
            }
            catch (Exception exc)
            {
                string errorXml = string.Format(CultureInfo.InvariantCulture, "<error>{0}</error>", exc.ToString());
                returnVal.LoadXml(errorXml);
            }

            return (returnVal);
        }


    }
}
